package com.wyb.service.impl;

import com.wyb.mapper.UserMapper;
import com.wyb.pojo.LoginUser;
import com.wyb.constant.Result;
import com.wyb.pojo.User;
import com.wyb.service.UpdateUserServcie;
import com.wyb.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class UpdateUserServiceImpl implements UpdateUserServcie {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Result updateAvatar(int id, String avatar) {



        int i = userMapper.updateAvatar(id, avatar);
        if(i!=0){
            LoginUser loginUser = redisCache.getCacheObject("login:" + id);
            User user = loginUser.getUser();
            user.setAvatar(avatar);
            loginUser.setUser(user);
            redisCache.setCacheObject("login:"+id, loginUser);
            return new Result(200, "成功修改头像");
        }else{
            return new Result(201, "头像修改失败，可能是一个错误的id导致");
        }

    }

    @Override
    @Transactional
    public Result updateUser(User user) {

        LoginUser loginUser = redisCache.getCacheObject("login:" + user.getId());
        if(Objects.isNull(loginUser)){
            return new Result(403, "你无权修改其他用户的个人信息", null);
        }
        loginUser.setUser(user);
        int i = userMapper.updateById(user);
        System.out.println(i);

        redisCache.setCacheObject("login:"+user.getId(),loginUser);
        return i !=0 ? new Result(200, "个人信息修改成功",  null)
                : new Result(201, "修改失败", null);

    }
}
